package com.example.springwebmvcdemo.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/header")
public class HeaderController {
    //获取Cookie
    //Cookie可以在浏览器或者postman手动设置
    @RequestMapping("/getCookie1")
    public String getCookie1(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        //TODO 空指针处理
        for (Cookie cookie: cookies) {
            System.out.println(cookie.getName() + ":" + cookie.getValue());
        }
        return "获取Cookie成功";
    }

    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("bite") String userValue) {
        return "获取Cookie成功,username: " + userValue;
    }

    //设置Session
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("userName","虚霄尊者");
        session.setAttribute("age",20);
        return "设置Session完毕!";
    }

    //获取Session
    @RequestMapping("/getSession1")
    public String getSession1(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute("userName");
        Integer age = (Integer) session.getAttribute("age");
        return "获取Session信息,userName: " + userName + ", age: " + age;
    }

    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session) {
        String userName = (String) session.getAttribute("userName");
        Integer age = (Integer) session.getAttribute("age");
        return "获取Session信息,userName: " + userName + ", age: " + age;
    }

    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute("userName") String userName) {
        return "获取Session信息,userName: " + userName;
    }

    //获取Header中内容
    @RequestMapping("/getHeader1")
    public String getHeader1(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return "User-Agent: " + userAgent;
    }

    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent) {
        return "User-Agent: " + userAgent;
    }

}
